"use client";
import DragAndDropUpload from "../components/DragAndDropUpload";
import BookMetaList from "../components/BookMetaList";
import { useEffect, useState } from 'react';
import SearchInput from "../components/SearchInput";
import BookList from "../components/BookList";

export default function Calibre() {

    const [bookItem, setBookItem] = useState("");
    const [envVar, setEnvVar] = useState({ API_BASE_URL: "http://localhost:7775" });
    const [searchQption, setSearchOption] = useState({
        type: "all",
        query: ""
    });
    const [isLoading, setIsLoading] = useState(false);
    // 使用useState钩子定义一个标志，用来判断是否是初始化渲染
    const [isInitialRender, setIsInitialRender] = useState(true);
    const [bookMeta, setBookMeta] = useState({
        author: [],
        bookLang: [],
        series: [],
        bookFormat: [],
        bookPublish: [],
        bookRate: [],
        bookTag: [],
        tagCode: [],
        books: []
    });

    const [books, setBooks] = useState([]);

    useEffect(() => {
        fetch('/api/env')
            .then(response => response.json())
            .then(data => {
                console.log(data);
                setEnvVar(data)
            })
            .catch(error => console.error('Error fetching environment variable:', error));
    }, []);


    const fetchItems = async () => {


        const response = await fetch(envVar['API_BASE_URL'] +'/calibre/api/book/list');
        if (!response.ok) {
            throw new Error('Failed to fetch data');
        }
        return response.json();
    };


    useEffect(() => {
        const loadItems = async () => {
            setIsLoading(true);
            try {
                const data = await fetchItems();
                console.log(data);
                setBookMeta(data.data);
                setBooks(data.data.books);
            } catch (error) {
                console.error('Error loading items:', error);
            }
            setIsLoading(false);
        };

        loadItems();
    }, [envVar]);

    useEffect(() => {
        if (isInitialRender) {
            // 如果是初始化渲染，则不执行任何操作
            setIsInitialRender(false); // 更新标志，后续渲染不再是初始化
        } else {
            const searcBooks = async () => {
                fetch(envVar['API_BASE_URL'] +"/calibre/api/book/query", {
                    method: "POST",
                    headers: {
                        'Content-Type': 'application/json'
                        // 'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: JSON.stringify(searchQption)

                }).then(async (response) => {
                    var data = await response.json();

                    setBooks(data.data)
                })
                    .catch((error) => console.error("Error:", error));
            };
            searcBooks();
        }

    }, [envVar,searchQption])


    const handleFileUpload = (files) => {
        // 在这里处理文件上传逻辑
        // 例如，你可以使用 FormData 将文件发送到 API 路由或外部服务器
        Array.from(files).forEach((file) => {
            console.log('上传文件:', file.name);

            // 创建一个 FormData 实例
            const formData = new FormData();
            formData.append('file', file);

            // 发送 POST 请求到 API 路由或外部服务器
            // fetch('/api/upload', {
            //   method: 'POST',
            //   body: formData,
            // })
            //   .then((response) => response.json())
            //   .then((data) => console.log('上传成功:', data))
            //   .catch((error) => console.error('上传失败:', error));

            // 注意：在 Next.js 中，如果你使用 API 路由，确保在 pages/api 目录下创建了相应的路由处理文件。
        });
    };

    const handleBookItemClick = (type, bookItem) => {
        setSearchOption({
            type: type,
            query: bookItem
        })
        // setBookItem(bookItem);
    }

    const handleSearch=(search)=>{
        setSearchOption(search)
    }

    return <>

        <SearchInput handleSearch={handleSearch}></SearchInput>

        <div className="flex">
            <div>
                <BookMetaList onItemClick={handleBookItemClick} bookMeta={bookMeta}>

                </BookMetaList>
            </div>

            <div className="flex-1">
                <DragAndDropUpload onFileUpload={handleFileUpload}>
                    <BookList books={books}></BookList>
                </DragAndDropUpload>

            </div>

        </div>

    </>
}